<?php

namespace App\Jobs;

use App\Http\service\GzhService;
use App\Models\Gzh;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

class TaskGzhJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $gzhservice;
    private $openids;
    private $gzhModels;
    private $localOpenIDs=[];

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->gzhservice=new GzhService();
        $next_openid=null;
        $this->gzhModels=new Gzh();
        $this->localOpenIDs=$this->gzhModels->pluck("openid");
        if(count($this->localOpenIDs)==0){
            $this->localOpenIDs=[];
        }else{

            $this->localOpenIDs=(array)$this->localOpenIDs;
        }
        $this->getGzhUser($next_openid);
    }

    private function getGzhUser($nextOpenid=null)
    {
        $user=$this->gzhservice->getUser($nextOpenid);
        $count=$user["count"];
        $nextOpenid=$user["next_openid"];
        $this->openids=$user["data"]["openid"];
        if ($count>0){
            $arr=[];
            foreach ($this->openids as $key=>$value){
                $arr[]=$value;
            }
            $this->openids_update($arr);
        }
        if($count>=10000){
            $this->getGzhUser($nextOpenid);
        }
    }

    private function openids_update($openids)
    {
        $this->localOpenIDs=$this->gzhModels->whereIn("openid",$openids)->select(["openid"])->get();
        $this->localOpenIDs=collect($this->localOpenIDs);
        foreach ($openids as $key=>$value){
            $res=$this->localOpenIDs->where("openid",$value)->first();
            if (!$res){
                $user=$this->gzhservice->getOneUser($value);
                if (isset($user["openid"])&&isset($user["unionid"])){
                    $users=[
                        "openid"=>$value,
                        "unionid"=>$user["unionid"]
                    ];
                    $this->gzhModels->create($users);
                }
            }
        }

    }



}
